<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use Illuminate\Support\Facades\DB;

class Area extends BaseModel
{
    protected $table = "sys_areas";

    public static function saveAsJsonFile2()
    {
        $items = [];
        $ss = self::findAllSS();


        foreach ($ss as $sk=>$s){

            $ks = $s->value.'0000';

            $row1 = ['name'=>$s->label,'value'=>$ks,'child'=>[]];

            $dj = self::findAllDJBySS($s->value);

            foreach ($dj as $dk=>$d){
                $kd = $s->value.$d->value;
                $row2 = ['name'=>$d->label,'value'=>$kd.'00','child'=>[]];

                $xj = self::findAllXJBySSAndDJ($s->value,$d->value);

                foreach ($xj as $xk=>$x){
                    $row2['child'][] =  ['name'=>$x->label,'value'=>$kd.$x->value];
                }
                $row1['child'][] = $row2;
            }
            $items[] = $row1;
        }

        Helpers::saveTempJson($items,'areas2');
        return $items;
    }

    public static function saveAsJsonFile1()
    {
        $items = [];

        $ss = self::findAllSS();

        foreach ($ss as $sk=>$s){

            $ks = $s->label.'0000';
            $items[$ks] = ['name'=>$s->label,'child'=>[]];

            $dj = self::findAllDJBySS($s->label);

            foreach ($dj as $dk=>$d){

                $kd = $s->label.$d->label;
                $items[$ks]['child'][$kd.'00'] = ['name'=>$d->label,'child'=>[]];

                $xj = self::findAllXJBySSAndDJ($s->label,$d->label);

                foreach ($xj as $xk=>$x){
                    $items[$ks]['child'][$kd.'00']['child'][] = [ $kd.$x->value=>$x->label];
                }
            }
        }

        Helpers::saveTempJson($items,'areas');

        return $items;
    }

    public static function findByCode($code)
    {
        return self::where('QXDM','=',$code)->first();
    }

    public function getAreaNameAttribute()
    {
        $name = str_replace(["|市辖区|","|县|","|其他|其他"],'',$this->QXMC);
        return str_replace('|',"",$name);
    }

    public static function findAllSS()
    {
        return DB::table('sys_areas')->where('DJSDM','=','00')->where('XJSDM','=','00')->groupBy('SSDM')
            ->orderBy('SSDM','asc')
            ->select('SSDM as value','SSMC as label')->get();
    }

    public static function findAllDJBySS($ssdm)
    {
        return DB::table('sys_areas')->where('SSDM','=',$ssdm)->where('XJSDM','=','00')->groupBy('DJSDM')
            ->orderBy('SSDM','asc')->orderBy('DJSDM','asc')
            ->select('DJSDM as value','DJSMC as label')->get();
    }

    public static function findAllXJBySSAndDJ($ssdm,$djsdm)
    {
        return DB::table('sys_areas')->where('SSDM','=',$ssdm)->where('DJSDM','=',$djsdm)
            ->orderBy('XJSDM','asc')
            ->select('XJSDM as value','XJSMC as label')->get();
    }
}
